package com.zone.module_base.server

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import com.arialyy.annotations.Download
import com.arialyy.aria.core.Aria
import com.arialyy.aria.core.task.DownloadTask

class DownloadService : Service() {
    private val map = HashMap<String, Long>()

    override fun onBind(intent: Intent): IBinder {
        return object : Binder() {
            fun startTask(url: String, dirPath: String? = "", threadNum: Int? = 1) {
                val taskId = Aria.download(this@DownloadService)
                    .load(url)
                    .setFilePath("$dirPath/${url.substringAfterLast("/")}")
                    .create()
                map[taskId.toString()] = taskId
            }
        }
    }


    @Download.onTaskComplete
    fun onDownloadSuccess(task: DownloadTask) {
        map.remove(task.key)
        Log.v("test", "DownloadService 下载完成:" + task.filePath)
    }

    @Download.onTaskFail
    fun onDownloadError(task: DownloadTask) {
        Log.v("test", "DownloadService 下载失败:" + task.taskName)
    }

    @Download.onTaskCancel
    fun onDownloadCancel(task: DownloadTask) {
        Log.v("test", "DownloadService 下载取消:" + task.key)
    }

    override fun onDestroy() {
        super.onDestroy()
        Aria.download(this).unRegister()
    }
}